/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.resource;

import java.util.Calendar;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.service.resource.ResPauseService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.utils.CrontabUtil;
import com.sinodata.bsm.common.utils.DateUtil;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResPauseRule;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author fanshengchao
 * @version 1.0
 * 
 * <p>
 * History:
 * 
 * Date Author Version Description
 * ---------------------------------------------------------------------------------
 * 2012-7-3 上午09:34:34 fanshengchao 1.0 To create
 * </p>
 * 
 * @since
 * @see
 */
public class ResPauseAction extends BaseAction<ResPauseRule> {

    private ResPauseRule entity;
    private Long id;

    @Autowired
    private ResPauseService resPauseService;

    /*
     * (non-Javadoc)
     * 
     * @see com.sinodata.bsm.center.web.action.BaseAction#delete()
     */
    @Override
    public String delete() throws Exception {
        resPauseService.deleteResPauseRule(id);
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {

        return "input";
    }

    /**
     * 资源暂停规则列表
     */
    @Override
    public String list() throws Exception {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        List<ResPauseRule> pauseRules = resPauseService.findRuleByResId(resId);
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        for (int i = 0; pauseRules != null && i < pauseRules.size(); i++) {
            ResPauseRule pauseRule = pauseRules.get(i);
            JSONObject entity = new JSONObject();
            entity.element("operate", "");
            entity.element("type", pauseRule.getType().intValue() == ResConstants.RES_PAUSE_TYPE_CYC ? "周期暂停" : "定期暂停");
            StringBuffer ruleValue = new StringBuffer("");

            String weekValue = pauseRule.getRule();
            if (pauseRule.getType().intValue() == ResConstants.RES_PAUSE_TYPE_CYC) { // 周期暂停
                ruleValue.append("在 " + CrontabUtil.CronParser(weekValue.split("@")[0]) + " 开始进行资源周期暂停,持续 " + CrontabUtil.parseSimple(Integer.parseInt(weekValue.split("@")[1])) + " 后恢复监控");
            } else if (pauseRule.getType().intValue() == ResConstants.RES_PAUSE_TYPE_TIM) { // 定时暂停
                Long begin = Long.parseLong(weekValue.split("@")[0]);
                if (weekValue.split("@").length > 1) {
                    ruleValue.append("从" + getDateTime(begin) + " 开始暂停 ");
                    Long end = Long.parseLong(weekValue.split("@")[1]);
                    ruleValue.append("至 " + getDateTime(end) + "结束");
                } else {
                    ruleValue.append("从 " + getDateTime(begin) + " 开始进行暂停至手动恢复监控 ");
                }
            } else {
                // 完全暂停
                entity.element("type", "完全暂停");
                ruleValue.append("从 " + getDateTime(Long.parseLong(weekValue)) + " 开始进行永久暂停至手动恢复监控 ");
            }

            entity.element("rule", ruleValue.toString());
            entity.element("id", pauseRule.getId());
            array.add(entity);
        }

        json.element("aaData", array);
        json.element("iTotalRecords", 0);
        json.element("iTotalDisplayRecords", 0);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new ResPauseRule();
        } else {
            entity = resPauseService.findById(id);
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.sinodata.bsm.center.web.action.BaseAction#save()
     */
    @Override
    public String save() throws Exception {
        if (entity.getType().intValue() == ResConstants.RES_PAUSE_TYPE_TIM) {
            String beginTime = entity.getRule().split("@")[0];
            String endTime = "";
            if (entity.getRule().split("@").length > 1) {
                endTime = entity.getRule().split("@")[1];
            }
            entity.setRule(DateUtil.getDateMillis(beginTime) + "@" + (endTime.equals("") ? "" : DateUtil.getDateMillis(endTime.toString())));
        } else if (entity.getType().intValue() == ResConstants.RES_PAUSE_TYPE_ALL) {
            entity.setRule(DateUtil.getDateMillis(entity.getRule()) + "");
        }
        resPauseService.saveOrUpdateResPauseRule(entity);
        return null;
    }

    public String pause() throws Exception {
        Long resId = Long.parseLong(Struts2Utils.getParameter("id"));
        Res res = ResBean.get(resId).res();
        List<ResPauseRule> pauseRules = resPauseService.findRuleByResId(resId);

        // 判断当前资源是否处于暂停状态
        ResPauseRule pauseRule = resPauseService.currentPausedResRule(resId);

        Struts2Utils.setRequestAttribute("pauseRules", pauseRules);
        Struts2Utils.setRequestAttribute("res", res);
        Struts2Utils.setRequestAttribute("pauseRule", pauseRule);
        return this.SUCCESS;
    }

    /***************************************************************************
     * 修改页面 并且初始化修改数据
     * 
     * @return
     */
    public String initUpdate() {
        Long id = Long.parseLong(Struts2Utils.getParameter("id"));
        ResPauseRule pauseRule = resPauseService.findById(id);
        Struts2Utils.setRequestAttribute("pauseRule", pauseRule);
        return "update";
    }

    /**
     * 恢复监控
     * 
     * @return
     */
    public String resume() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        Res res = ResBean.get(resId).res();
        resPauseService.resumeResPaused(res);
        return null;
    }

    /**
     * 完全暂停
     * 
     * @return
     */
    public String completePause() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        ResPauseRule rule = new ResPauseRule();
        rule.setResId(resId.longValue());
        rule.setStatus(1);
        rule.setType(ResConstants.RES_PAUSE_TYPE_ALL);
        resPauseService.saveOrUpdateResPauseRule(rule);
        return null;
    }

    /**
     * 和DateUtil类里面的getDateTime方法相同,最后返回的数据不包含秒
     * 
     * @param millis
     *            格式化后13个长度的数据
     * @return 页面人性化的回显数据
     */
    public String getDateTime(long millis) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(new java.util.Date(millis));
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH) + 1;
        int day = rightNow.get(Calendar.DAY_OF_MONTH);
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        int minute = rightNow.get(Calendar.MINUTE);
        String strDateTime = year + "-" + (month < 10 ? "0" + month + "-" : month + "-") + (day < 10 ? "0" + day + " " : day + " ") + (hour < 10 ? "0" + hour + ":" : hour + ":") + (minute < 10 ? "0" + minute : minute);
        return strDateTime;
    }

    /**
     * 规则是否删除
     * 
     * @return true:已删除 false:未删除
     */
    public String isDelete() {
        Struts2Utils.renderText(" " + (resPauseService.findById(id) == null) + " ");
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public ResPauseRule getModel() {
        // TODO Auto-generated method stub
        return entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
